import {
  APP_VER,
  APP_BASE_URL,
  HEADER_TOKEN_PREFIX
} from '../config'
import {
  isH5Dev,
  isWx
} from './is.js'

import store from '../store'

import currency from '../plugins/currency.js'

export function get(url, params = {}, opts = {}) {
  if (opts.isShop) {
    params.shop_id = store('shop').shopId
  }
  // 是否async/await
  const isAsync = opts.isAsync || false
  if (isAsync) {
    return awaitTo(uni.$uv.http.get(url, { params }))
  } else {
    return uni.$uv.http.get(url, { params })
  }
}

export function post(url, data = {}, opts = {}) {
  if (opts.isShop) {
    data.shop_id = store('shop').shopId
  }
  // 是否async/await
  const isAsync = opts.isAsync || false
  if (isAsync) {
    return awaitTo(uni.$uv.http.post(url, data))
  } else {
    return uni.$uv.http.post(url, data)
  }
}

export async function getList(api, data = {}, format) {
  const res = await get(api, data || {})
  if (res?.success) {
    /** 根据接口获取列表数据 format参数可格式化数据 */
    return typeof format === 'function' ? format(res.data) : res.data
  }
  return null
}

// 乘法函数，用来得到精确的乘法结果
// 说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
// 调用：$h.Mul(arg1,arg2)
// 返回值：arg1乘以arg2的精确结果
export function Mul(arg1, arg2) {
  arg1 = parseFloat(arg1)
  arg2 = parseFloat(arg2)
  var m = 0
  var s1 = arg1.toString()
  var s2 = arg2.toString()
  try {
    m += s1.split('.')[1].length
  } catch (e) {}
  try {
    m += s2.split('.')[1].length
  } catch (e) {}
  return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
}
// 加法函数，用来得到精确的加法结果
// 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
// 调用：$h.Add(arg1,arg2)
// 返回值：arg1加上arg2的精确结果
export function Add(arg1, arg2) {
  arg2 = parseFloat(arg2)
  var r1, r2, m
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(100, Math.max(r1, r2))
  return (Mul(arg1, m) + Mul(arg2, m)) / m
}
// 减法函数，用来得到精确的减法结果
// 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
// 调用：$h.Sub(arg1,arg2)
// 返回值：arg1减去arg2的精确结果
export function Sub(arg1, arg2) {
  arg1 = parseFloat(arg1)
  arg2 = parseFloat(arg2)
  var r1, r2, m, n
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  // 动态控制精度长度
  n = (r1 >= r2) ? r1 : r2
  return ((Mul(arg1, m) - Mul(arg2, m)) / m).toFixed(n)
}
// 除法函数，用来得到精确的除法结果
// 说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
// 调用：$h.Div(arg1,arg2)
// 返回值：arg1除以arg2的精确结果
export function Div(arg1, arg2) {
  arg1 = parseFloat(arg1)
  arg2 = parseFloat(arg2)
  var t1 = 0
  var t2 = 0
  var r1
  var r2
  try {
    t1 = arg1.toString().split('.')[1].length
  } catch (e) {
    console.log(e)
  }
  try {
    t2 = arg2.toString().split('.')[1].length
  } catch (e) {
    console.log(e)
  }
  r1 = Number(arg1.toString().replace('.', ''))
  r2 = Number(arg2.toString().replace('.', ''))
  return Mul(r1 / r2, Math.pow(10, t2 - t1))
}

export function awaitTo(promise, errMsg) {
  if (typeof promise?.then === 'function') {
    return promise.then(
      // 成功,返回[null,响应结果]
      data => [null, data]
    ).catch((err) => {
      // 失败,返回[错误信息,undefined]
      if (errMsg) {
        const parsedError = Object.assign({}, err, errMsg)
        return [parsedError, undefined]
      }
      return [err, undefined]
    })
  } else {
    return async function(...args) {
      try {
        return [null, await promise.apply(this, args)]
      } catch (err) {
        return [err]
      }
    }
  }
}

/**
 * [cache 本地缓存 同步, ceche(key, null)-> 删除指定key的缓存, ceche(, null)-> 删除所有缓存 ]
 * @param  {string} key [本地缓存中指定的key]
 * @param  {|null}   value   [本地缓存中指定的value, value=是取值, value=null是清除]
 * @param  {int} exp [缓存的有效时间]
 */
export function cache(key = '', value = '', exp = 0) {
  var time = getTime()
  var obj = {}
  key = APP_VER + key
  if (value === '') {
    obj = uni.getStorageSync(key)
    if (!obj) {
      return null
    } else if (obj.exp === 0 || obj.exp > time) {
      return obj.value
    } else {
      uni.removeStorageSync(key)
      return null
    }
  } else if (value === null) {
    if (key === APP_VER)
      uni.clearStorageSync()
    else
      uni.removeStorageSync(key)
    return true
  } else {
    obj = {
      value: value,
      exp: exp > 0 ? time + exp : 0
    }
    uni.setStorageSync(key, obj)
    return true
  }
}

/**
 * 获取时间戳,单位秒
 * dateStr[日期]
 * isMs[是否毫秒]
 */
export function getTime(dateStr = '', isMs = false) {
  let date
  if (dateStr) {
    date = new Date(dateStr)
  } else {
    date = new Date()
  }
  return Date.parse(date) / isMs ? 1 : 1000
}

// 获取当前时间，格式YYYY-MM-DD
export function formatDate(time = 0, format = 'YYYY-mm-dd HH:ii:ss') {
  let date
  if (time) {
    if (typeof time === 'number') {
      let multiple = time.toString().length === 10 ? 1000 : 1
      date = new Date(time * multiple)
    } else {
      date = new Date(time)
    }
  } else {
    date = new Date()
  }
  var map = {
    m: date.getMonth() + 1, // 月份
    d: date.getDate(), // 日
    H: date.getHours(), // 小时
    i: date.getMinutes(), // 分
    s: date.getSeconds(), // 秒
    q: Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  }
  format = format.replace(/([YmdHisqS])+/g, function(all, t) {
    var v = map[t]
    if (v !== undefined) {
      if (all.length > 1) {
        v = '0' + v
        v = v.substr(v.length - 2)
      }
      return v
    } else if (t === 'Y') {
      return date.getFullYear().toString().substr(4 - all.length)
    }
    return all
  })
  return format
}

// 下拉滑动更多状态
export function getLoading(loading) {
  return ['more', 'loading', 'nomore'][loading]
}

export function wxConfig(data = {}) {
  jWeixin.config(data)
}

export function wxpay(data = {}) {
  return new Promise((resolve, reject) => {
    data.success = resolve
    data.fail = reject
    // #ifdef H5
    if (data.timeStamp && !data.timestamp) {
      data.timestamp = data.timeStamp
    }
    jWeixin.chooseWXPay(data)
    // #endif
    // #ifndef H5
    if (data.timestamp && !data.timeStamp) {
      data.timeStamp = data.timestamp
    }
    uni.getProvider({
      service: 'payment',
      success: function(pro) {
        data.provider = pro.provider
        uni.requestPayment(data)
      }
    })
    // #endif
  })
}

export function uploadFile(filePath, url = '/upload/uploadImage', fieldName = 'file') {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: APP_BASE_URL + url,
      filePath: filePath,
      name: fieldName,
      header: {
        Authorization: HEADER_TOKEN_PREFIX + store.getters.token,
        Accept: 'application/json, text/plain, */*'
      },
      formData: {},
      success(res) {
        if (res.statusCode === 200) {
          var data = JSON.parse(res.data)
          resolve(data)
        } else {
          reject(res)
        }
      },
      fail(err) {
        reject(err)
      }
    })
  })
}

export function chooseImage(obj = {}, url = '', fieldName = 'file') {
  return new Promise((resolve, reject) => {
    obj.success = res => {
      let arr = []
      let index = 0
      let files = res.tempFilePaths
      let length = files.length

      function upload() {
        uni.uploadFile({
          url: APP_BASE_URL + url,
          filePath: files[index],
          name: fieldName,
          header: {
            Authorization: 'Bearer' + store.getters.token
          },
          formData: {},
          success: res2 => {
            if (res2.statusCode === 200) {
              var data = typeof res2.data === 'string' ? JSON.parse(res2.data) : res2.data
              arr.push(data)
            }
            index++
          },
          complete: () => {
            index < length ? upload() : resolve(arr)
          }
        })
      }
      upload()
    },
    obj.fail = reject
    uni.chooseImage(obj)
  })
}

export function chooseFile(obj = {}, url = '', fieldName = 'file') {
  return new Promise((resolve, reject) => {
    obj.count = obj.count || 1
    obj.type = obj.type || 'file'
    obj.success = function(res) {
      let arr = []
      let index = 0
      let files = res.tempFiles
      let length = files.length

      function upload() {
        uploadFile(files[index].path, url, fieldName).then(res2 => {
          arr.push(res2)
        }, err => {
          console.log(err)
        }).finally(() => {
          index++
          index < length ? upload() : resolve(arr)
        })
      }
      upload()
    }
    obj.fail = reject
    uni.chooseFile(obj)
  })
}

export function chooseMessageFile(obj = {}, url = '', fieldName = 'file') {
  return new Promise((resolve, reject) => {
    obj.count = obj.count || 1
    obj.type = obj.type || 'file'
    obj.success = function(res) {
      let arr = []
      let index = 0
      let files = res.tempFiles
      let length = files.length

      function upload() {
        console.log(files[index], url, fieldName)
        uploadFile(files[index].path, url, fieldName).then(res2 => {
          arr.push(res2)
        }, err => {
          console.log(err)
        }).finally(() => {
          index++
          index < length ? upload() : resolve(arr)
        })
      }
      upload()
    }
    obj.fail = reject
    wx.chooseMessageFile(obj)
  })
}

// 预览图片
export function previewImage(urls, current = 0) {
  return new Promise((resolve, reject) => {
    if (typeof urls === 'string') urls = [urls]
    let obj = {
      current: current === 'string' && current ? current : urls[current],
      urls,
      success: resolve,
      fail: reject
    }
    if (isWx()) {
      jWeixin.previewImage(obj)
    } else {
      uni.previewImage(obj)
    }
  })
}

export function saveImage(url) {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url,
      success: res => {
        if (res.statusCode !== 200) return reject
        else return uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: resolve,
          fail: reject
        })
      },
      fail: reject
    })
  })
}

export function getImageInfo(src) {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src,
      success: resolve,
      fail: reject
    })
  })
}

export function getLocation(obj = {}) {
  return new Promise((resolve, reject) => {
    obj.success = resolve
    obj.fail = reject
    if (isH5Dev()) {
      resolve({
        latitude: 0,
        longitude: 0
      })
    } else if (isWx()) {
      jWeixin.getLocation(obj)
    } else {
      uni.getLocation(obj)
    }
  })
}

export function openLocation(obj = {}) {
  return new Promise((resolve, reject) => {
    if (typeof obj.latitude === 'string') obj.latitude = Number(obj.latitude)
    if (typeof obj.longitude === 'string') obj.longitude = Number(obj.longitude)
    if (!obj.latitude) obj.latitude = 39.5427
    if (!obj.longitude) obj.longitude = 116.2317
    obj.success = resolve
    obj.fail = reject
    if (isWx()) {
      jWeixin.openLocation(obj)
    } else {
      uni.openLocation(obj)
    }
  })
}

export function scanQRCode(obj = {}) {
  return new Promise((resolve, reject) => {
    obj.success = resolve
    obj.fail = reject
    // #ifdef H5
    if (isH5Dev()) {
      return resolve({
        result: '自定义扫码内容'
      })
    } else if (isWx()) {
      obj.needResult = obj?.needResult ?? 1
      obj.scanType = obj?.scanType ?? ['qrCode', 'barCode']
      jWeixin.scanQRCode(obj)
    }
    // #endif
    // #ifdef MP
    uni.scanCode(obj)
    // #endif
  })
}

export function wxLogin(obj = {}) {
  return new Promise((resolve, reject) => {
    obj.provider = obj?.provider ?? 'weixin'
    obj.success = resolve
    obj.fail = reject
    uni.login(obj)
  })
}

export function wxUserProfile(obj = {}) {
  return new Promise((resolve, reject) => {
    if (obj.desc) obj.desc = '用于完善会员资料'
    obj.success = resolve
    obj.fail = reject
    uni.getUserProfile(obj)
  })
}

// 页面滚动到置顶位置
export function scrollTo(val = 0) {
  uni.pageScrollTo({
    scrollTop: val,
    duration: 100
  })
}

export function telCall(phone = '') {
  uni.makePhoneCall({
    phoneNumber: phone
  })
}

export function toast(obj = {}, delayed = 0) {
  if (typeof obj === 'string') {
    obj = {
      title: obj
    }
  }
  if (!obj?.icon) {
    obj.icon = 'none'
  }
  if (delayed) {
    setTimeout(function() {
      uni.showToast(obj)
    }, delayed)
  } else {
    uni.showToast(obj)
  }
}

export function showModal(obj = {}) {
  return new Promise((resolve, reject) => {
    obj.success = resolve
    obj.fail = reject
    uni.showModal(obj)
  })
}

/**
 * opt  object | string
 * to_url object | string
 * 例:
 * Tips(/pages/test/test); 跳转不提示
 * Tips({title:提示},/pages/test/test); 提示并跳转
 * Tips({title:提示},{tab:1,url:/pages/index/index}); 提示并跳转值table上
 * tab=1 一定时间后跳转至 table上
 * tab=2 一定时间后跳转至非 table上
 * tab=3 一定时间后返回上页面
 * tab=4 关闭所有页面跳转
 * tab=5 关闭当前页面跳转至非table上
 */
export function tips(opt, to_url) {
  if (typeof opt === 'string') {
    to_url = opt
    opt = {}
  }
  let title = opt.title || ''
  let icon = opt.icon || 'none'
  let endtime = opt.endtime || 1000
  let success = opt.success
  if (title) uni.showToast({
    title: title,
    icon: icon,
    duration: endtime,
    success
  })
  if (typeof to_url !== undefined) {
    if (typeof to_url === 'object') {
      let tab = to_url.tab || 1
      let url = to_url.url || ''
      switch (tab) {
        case 1:
          // 一定时间后跳转至 table
          setTimeout(function() {
            uni.switchTab({
              url: url
            })
          }, endtime)
          break
        case 2:
          // 跳转至非table页面
          setTimeout(function() {
            uni.navigateTo({
              url: url
            })
          }, endtime)
          break
        case 3:
          // 返回上页面
          setTimeout(function() {
            // #ifndef H5
            uni.navigateBack({
              delta: parseInt(url)
            })
            // #endif
            // #ifdef H5
            history.back()
            // #endif
          }, endtime)
          break
        case 4:
          // 关闭当前所有页面跳转至非table页面
          setTimeout(function() {
            uni.reLaunch({
              url: url
            })
          }, endtime)
          break
        case 5:
          // 关闭当前页面跳转至非table页面
          setTimeout(function() {
            uni.redirectTo({
              url: url
            })
          }, endtime)
          break
      }
    } else if (typeof to_url === 'function') {
      setTimeout(function() {
        to_url && to_url()
      }, endtime)
    } else {
      // 没有提示时跳转不延迟
      setTimeout(function() {
        uni.navigateTo({
          url: to_url
        })
      }, title ? endtime : 0)
    }
  }
}

// 返回上一页
export function onBack() {
  let pages = getCurrentPages()
  if (pages.length === 1) {
    uni.switchTab({
      url: '/pages/index/index'
    })
  } else {
    uni.navigateBack({})
  }
}

export function getAppSharePath(url = '', data = {}) {
  let pages = getCurrentPages()
  let currentPage = pages[pages.length - 1]
  let {
    route,
    options
  } = currentPage
  let param = {
    ...options,
    ...data
  }
  let query = ''
  for (let i in param) {
    query += `&${i}=${param[i]}`
  }
  return `/${url || route}` + query.replace('&', '?')
}

export function getShareLink(link = '', options = {}) {
  if (!link) link = window.location.href
  link = link.replace(new RegExp('&amp;', 'g'), '&')
  let [host, hash] = link.split('#')
  // let [path, query] = host.split('?')
  let path = ''
  let query = ''
  let hostArr = host.split('?')
  hostArr.forEach((item, i) => {
    if (i) {
      query += item
    } else {
      path = item
    }
  })
  // link = `${path || ''}?${query || ''}#${hash || '/'}`
  link = `${path || ''}?${query || ''}`
  if (hash) {
    link += `#${hash}`
  }
  let params = {}
  if (query) {
    let arr = query.split('&')
    let filter = ['pid', 'code', 'state']
    for (var i = 0; i < arr.length; i++) {
      let pair = arr[i].split('=')
      let val = trim(pair[1], '/')
      if (val && !filter.some(item => pair[0].indexOf(item) !== -1)) {
        params[pair[0]] = val
      }
    }
  }
	
	const userId = store('user').info?.id
  if (userId) params.pid = userId
  
  params = {
    ...params,
    ...options
  }
  let urlRes = ''
  if (JSON.stringify(params) === '{}') {
    urlRes = link.replace(`?${query}`, '')
  }
  let requery = JSON.stringify(params).replace(/["{}]/g, '').replace(/:/g, '=').replace(/,/g, '&')
  if (query) {
    urlRes = link.replace(query, requery)
  } else {
    let repath = ~host.indexOf('?') ? `${path}?` : path
    urlRes = link.replace(repath, `${path}?${requery}`)
  }
  return urlRes.replace('??', '?')
}

export function wxShare(obj = {}, delay = 300) {
  // #ifdef MP
  let path = getAppSharePath()
  return {
    title: obj.title ? obj.title : '分享标题',
    imageUrl: obj.imageUrl ? obj.imageUrl : '',
    path: obj.path ? obj.path : path
  }
  // #endif
	
	// #ifdef H5
	return new Promise(async (resolve, reject) => {
		const appStore = store('app')
		if (!appStore.share.share_title) {
			const shareRes = await get('/index/wxShare')
			appStore.setShare(shareRes.data)
		}
		const {title: share_title, desc: share_desc, img: share_logo} = appStore.share
	  obj.success = resolve
	  obj.fail = reject
	  obj.cancel = reject
	  if (!obj.title) obj.title = share_title
	  if (!obj.desc) obj.desc = share_desc
	  if (!obj.imgUrl) obj.imgUrl = share_logo
	
	  let maxSize = 80
	  obj.desc = obj.desc.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, '').replace(/ +/g, ' ').replace(/\r\n/g, ' ').replace(/\n/g, ' ')
	  obj.desc = obj.desc.length > maxSize ? (obj.desc.substr(0, maxSize) + '...') : obj.desc
	  if (obj.lineDesc) {
	    obj.lineDesc = obj.lineDesc.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, '').replace(/ +/g, ' ').replace(/\r\n/g, ' ').replace(/\n/g, ' ')
	    obj.lineDesc = obj.lineDesc.length > maxSize ? (obj.lineDesc.substr(0, maxSize) + '...') : obj
	      .lineDesc
	  }
		console.log(getShareLink(obj.link))
	  return setTimeout(() => {
	    return jWeixin.ready(function() {
	      obj.link = getShareLink(obj.link)
	      jWeixin.onMenuShareAppMessage(obj) // 分享给朋友
	      // var line = JSON.parse(JSON.stringify(obj));
	      var line = { ...obj, title: obj.lineDesc ? obj.lineDesc : obj.desc }
	      // line.title = line.desc;
	      jWeixin.onMenuShareTimeline(line) // 分享给朋友圈
	    })
	  }, delay)
	})
	// #endif
}

export function genRandom(min, max) {
  return Math.floor((Math.random() * (max - min + 1))) + min
}

export function formatFloor(value) {
  return Math.floor(value * 100) / 100
}

export function toTree(data = [], pidField = 'pid', childrenField = 'children') {
  // 删除 所有 children,以防止多次调用
  data.forEach((item) => {
    item[childrenField] = []
  })

  // 将数据存储为 以 id 为 KEY 的 map 索引数据列
  const map = {}
  data.forEach((item) => {
    map[item.id] = item
  })
  //        console.log(map);
  const val = []
  data.forEach((item) => {
    // 以当前遍历项，的pid,去map对象中找到索引的id
    const parent = map[item[pidField]]
    // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
    if (parent) {
      (parent[childrenField] || (parent[childrenField] = [])).push(item)
    } else {
      // 如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
      val.push(item)
    }
  })
  return val
}

// 递归查询父元素
export function findTreeParents(list, id) {
  for (let i = 0; i < list.length; i++) {
    if (list[i].id === id) {
      // 查询到返回该数组对象
      return [{ id: list[i].id, index: i }]
    }
    if (list[i].children) {
      let node = findTreeParents(list[i].children, id)
      if (node !== undefined) {
        // 查询到把父节点连起来
        return [{ id: list[i].id, index: i }, ...node]
      }
    }
  }
}

// add(加) || subtract(减) || multiply(乘) || divide(除) || distribute(均分)
export function sum(list, field) {
  return list.reduce((acc, cur) => currency(acc).add(field ? cur[field] : cur).value, 0)
}

export function getSize(w, h) {
  if (!h) h = w
  return {
    width: w * 2 + 'rpx',
    height: h * 2 + 'rpx'
  }
}

/**
 * 随机字符串
 */
export function randomStr(len) {
  var len = len || 6
  var t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  var a = t.length
  var n = ''
  for (let i = 0; i < len; i++) n += t.charAt(Math.floor(Math.random() * a))
  return n
}

/**
 * 获取url指定的参数
 */
export function getUrlParam(key = '', defaultVal) {
  let res = ''
  // #ifdef H5
  var query = window.location.search.substring(1).replace(new RegExp('&amp;', 'g'), '&')
  if (!query) {
    return ''
  }
  var vars = query.split('&')
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=')
    if (pair[0] === key) {
      res = pair[1]
    }
  }
  // #endif
  return res ? trim(res, '/') : (typeof defaultVal === 'undefined' ? '' : defaultVal)
}

/**
 * 删除url指定的参数
 */
export function delUrlParam(link = '', filter = '') {
  if (!link) link = window.location.href
  link = link.replace(new RegExp('&amp;', 'g'), '&')
  let [host, hash] = link.split('#')

  let path = ''
  let query = ''
  let hostArr = host.split('?')
  hostArr.forEach((item, i) => {
    if (i) {
      query += item
    } else {
      path = item
    }
  })
  link = `${path || ''}?${query || ''}`
  if (hash) {
    link += `#${hash}`
  }
  let params = {}
  if (query) {
    if (typeof filter === 'string') {
      filter = filter === '' ? [] : [filter]
    }
    let arr = query.split('&')
    for (var i = 0; i < arr.length; i++) {
      let pair = arr[i].split('=')
      let val = trim(pair[1], '/')
      if (val && !filter.some(item => pair[0].indexOf(item) !== -1)) {
        params[pair[0]] = val
      }
    }
  }

  if (!params.hasOwnProperty('pid')) params.pid = 0

  let urlRes = ''
  let requery = JSON.stringify(params)
    .replace(/["{}]/g, '')
    .replace(/:/g, '=')
    .replace(/,/g, '&')
  if (query) {
    urlRes = link.replace(query, requery)
  } else {
    let repath = ~host.indexOf('?') ? `${path}?` : path
    urlRes = link.replace(repath, `${path}?${requery}`)
  }
  return urlRes
}

/**
 * 移除左侧
 */
export function ltrim(str = '', char) {
  if (str === '') {
    return ''
  } else {
    var pos = str.indexOf(char)
    return ~pos ? str.substr(0, pos) : str
  }
}

/**
 * 移除右侧
 */
export function rtrim(str = '', char) {
  if (str === '') {
    return ''
  } else {
    var pos = str.lastIndexOf(char)
    return ~pos ? str.substr(0, pos) : str
  }
}

/**
 * 移除两侧
 */
export function trim(str = '', char) {
  if (str === '') {
    return ''
  } else {
    return rtrim(ltrim(str, char), char)
  }
}
